//
//  SafeViewController.m
//  location
//
//  Created by Dongxiang Xu on 2024/4/15.
//

#import "SafeViewController.h"
#import "NotifyViewController.h"
#import "HomeManageViewController.h"
#import "HomeViewController.h"
#import "XDXBaseTabBarViewController.h"
#import "SettingViewController.h"
#import "AppSettingViewController.h"
#import "ArriveLogViewController.h"
#import "CashViewController.h"
#import "EnterExitRegionLogViewController.h"
#import "PolicyWebViewController.h"
#import "HomeSheetPopView.h"
#import "UIImageView+WebCache.h"

@interface SafeViewController ()<MKMapViewDelegate>

@property (nonatomic,strong) UIImageView *head;
@property (nonatomic,strong) UILabel *nickName;
@property (nonatomic,strong) UIView *homeView;
//@property (nonatomic,strong) UIButton *homeButton;
@property (nonatomic,strong) UIButton *roomName;
@property (nonatomic,strong) UIImageView *roomIcon;
@property (nonatomic,strong) UIImageView *arrow;
@property (nonatomic,strong) UILabel *cashTitle;
@property (nonatomic,strong) UILabel *cashName;
@property (nonatomic,strong) UIButton *quickCash;
@property (nonatomic,strong) UIImageView *cashView;
@property (nonatomic,strong) UIView *infoView;
@property (nonatomic,strong) NSDictionary *groupInfo;

@end

@implementation SafeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationController.navigationItem.leftItemsSupplementBackButton = NO;
    self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 44, 44);                     // 控制触摸区域
    [backBtn setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    [[backBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [self.navigationController.navigationBar addSubview:backBtn];
    
    self.view.backgroundColor = LightBGColor;
    [self getVersion];
    [self initView];
    [self loadGroupListFromPlist];
}

- (void)initView
{
    _head = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-60)/2, STATUSHEIGHT+16, 60, 60)];
    _head.layer.masksToBounds = YES;
    [_head.layer setCornerRadius:24];
    _head.userInteractionEnabled = YES;
    _head.backgroundColor = GraryLightColor;
    [self.head sd_setImageWithURL:[NSURL URLWithString:[XDXShareInstance shareInstance].avatar]];
    [self.view addSubview:_head];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [[tap rac_gestureSignal] subscribeNext:^(id x) {
        SettingViewController *vc = [[SettingViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    [_head addGestureRecognizer:tap];
        
    _nickName = [[UILabel alloc] initWithFrame:CGRectMake(16, _head.maxY+12, SCREEN_WIDTH-32, 26)];
    _nickName.textColor = RealBlackColor;
    _nickName.font = REAL_MEDIUM_FONT(20);
    _nickName.textAlignment = NSTextAlignmentCenter;
    _nickName.userInteractionEnabled = YES;
    _nickName.text = [XDXShareInstance shareInstance].nickName;
    [self.view addSubview:_nickName];
    UITapGestureRecognizer *nameTap = [[UITapGestureRecognizer alloc] init];
    [[nameTap rac_gestureSignal] subscribeNext:^(id x) {
        SettingViewController *vc = [[SettingViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    [_nickName addGestureRecognizer:nameTap];
    
    _homeView = [[UIView alloc] initWithFrame:CGRectMake(16, _nickName.maxY+16, SCREEN_WIDTH-32, 72)];
    _homeView.userInteractionEnabled = YES;
    [_homeView.layer setCornerRadius:24];
    _homeView.layer.masksToBounds = YES;
    _homeView.backgroundColor = RealWhiteColor;
    [self.view addSubview:_homeView];
    UITapGestureRecognizer *homeTap = [[UITapGestureRecognizer alloc] init];
    [[homeTap rac_gestureSignal] subscribeNext:^(id x) {
        HomeSheetPopView *view = [[HomeSheetPopView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) StartY:CGRectGetMaxY(self.homeView.frame)+6 TGroupId:self.groupInfo[@"id"] IsManage:YES];
        [self.tabBarController.view addSubview:view];
        view.RoomManageBlock = ^{
            HomeManageViewController *vc = [[HomeManageViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        view.RoomManageClickBlock = ^(NSDictionary *groupInfo) {
            self.groupInfo = [NSDictionary dictionaryWithDictionary:groupInfo];
            [XDXShareInstance shareInstance].groupId = self.groupInfo[@"id"];
            [[NSUserDefaults standardUserDefaults] setValue:self.groupInfo[@"id"] forKey:GroupId];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [self.roomName setTitle:[NSString stringWithFormat:@"%@",self.groupInfo[@"name"]] forState:UIControlStateNormal];
            [self.roomName sizeToFit];
            [self.roomName setFrame:CGRectMake(24, 20, self.roomName.width, 32)];
            [self dealMemberGroupView];
            
            [((HomeViewController *)((UINavigationController *)self.tabBarController.childViewControllers.firstObject).visibleViewController) getGroupListSuccess:nil Error:nil];
        };
    }];
    [_homeView addGestureRecognizer:homeTap];
    
//    _homeButton = [[UIButton alloc] initWithFrame:_homeView.frame];
//    _homeButton.showsMenuAsPrimaryAction = YES; // 点按弹菜单
//    [self.view addSubview:_homeButton];
    
    _roomName = [[UIButton alloc] initWithFrame:CGRectMake(24, 0, _homeView.width-48, _homeView.height)];
    _roomName.userInteractionEnabled = NO;
    [_roomName setTitleColor:GraryHeavyLightColor forState:UIControlStateNormal];
    _roomName.titleLabel.font = REAL_MEDIUM_FONT(17);
    _roomName.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_homeView addSubview:_roomName];
    
    _roomIcon = [[UIImageView alloc] initWithFrame:CGRectMake(_roomName.maxX+4, (_homeView.height-22)/2, 22, 22)];
    [_homeView addSubview:_roomIcon];
    
    _arrow = [[UIImageView alloc] initWithFrame:CGRectMake(_homeView.width-36, (_homeView.height-12)/2, 12, 12)];
    _arrow.image = [UIImage imageNamed:@"home_arrow"];
    [_homeView addSubview:_arrow];
    
    _cashView = [[UIImageView alloc] initWithFrame:CGRectMake(16, _homeView.maxY+12, SCREEN_WIDTH-32, (SCREEN_WIDTH-32)*0.3081)];
    _cashView.userInteractionEnabled = YES;
    [self.view addSubview:_cashView];
    
    UITapGestureRecognizer *aaTap = [[UITapGestureRecognizer alloc] init];
    [[aaTap rac_gestureSignal] subscribeNext:^(id x) {
        CashViewController *vc = [[CashViewController alloc] init];
        vc.groupInfo = self.groupInfo;
        [self.navigationController pushViewController:vc animated:YES];
    }];
    [_cashView addGestureRecognizer:aaTap];
    
    _cashTitle = [[UILabel alloc] initWithFrame:CGRectMake(26, (SCREEN_WIDTH-32)*0.0702, _cashView.width-52, 22)];
    _cashTitle.textColor = [RealWhiteColor colorWithAlphaComponent:0.4];
    _cashTitle.font = REAL_MEDIUM_FONT(13);
    _cashTitle.hidden = YES;
    _cashTitle.text = @"当前家庭为";
    [_cashView addSubview:_cashTitle];
    
    _cashName = [[UILabel alloc] initWithFrame:CGRectMake(26, _cashTitle.maxY+2, _cashView.width-52, 26)];
    _cashName.textColor = RealWhiteColor;
    _cashName.font = REAL_MEDIUM_FONT(17);
    _cashName.hidden = YES;
    [_cashView addSubview:_cashName];
    
    _quickCash = [[UIButton alloc] initWithFrame:CGRectMake(_homeView.width-80, (SCREEN_WIDTH-32)*0.1243, 74, 32)];
    [_cashView addSubview:_quickCash];
    [[_quickCash rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        CashViewController *vc = [[CashViewController alloc] init];
        vc.groupInfo = self.groupInfo;
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    _infoView = [[UIView alloc] initWithFrame:CGRectMake(16, _homeView.maxY+24+(SCREEN_WIDTH-32)*0.3081, SCREEN_WIDTH-32, 144)];
    _infoView.layer.masksToBounds = YES;
    [_infoView.layer setCornerRadius:16];
    _infoView.backgroundColor = RealWhiteColor;
    [self.view addSubview:_infoView];
    
    NSArray *array = @[@{@"title":@"智能通知",@"img":@"bling"},@{@"title":@"帮助与反馈",@"img":@"help"},@{@"title":@"设置",@"img":@"setting"}];
    for (int i = 0; i < array.count; i++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, i*48, _infoView.width, 48)];
        [_infoView addSubview:button];
        
        [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if (i==0) {
                NotifyViewController *vc = [[NotifyViewController alloc] init];
                vc.groupInfo = self.groupInfo;
                [self.navigationController pushViewController:vc animated:YES];
            }else if (i==1) {
                PolicyWebViewController *vc = [[PolicyWebViewController alloc] initWithRelativePath:@"http://m.tanhuos.com/help_center.html"];
                vc.modalPresentationStyle = UIModalPresentationPageSheet;
                [self presentViewController:vc animated:YES completion:nil];
            }else if (i==2) {
                AppSettingViewController *vc = [[AppSettingViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }];
        
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(16, (button.height-24)/2, 24, 24)];
        img.image = [UIImage imageNamed:array[i][@"img"]];
        img.contentMode = UIViewContentModeScaleAspectFit;
        [button addSubview:img];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(img.maxX+6, 0, 80, button.height)];
        label.textColor = RealBlackColor;
        label.font = REAL_MEDIUM_FONT(15);
        label.text = array[i][@"title"];
        [button addSubview:label];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [((XDXBaseTabBarViewController *)self.tabBarController) xdx_showCustomTabBar];
    [self getUserInfo];
    [self getGroupList];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    if (self.navigationController.childViewControllers.count>1) {
        [((XDXBaseTabBarViewController *)self.tabBarController) xdx_hideCustomTabBar];
    }
}

// 从plist文件读取群组列表
- (void)loadGroupListFromPlist
{
    // 获取Documents目录路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"GroupList.plist"];
    
    // 检查文件是否存在
    if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
        // 从plist文件读取数据
        NSArray *loadedArray = [NSArray arrayWithContentsOfFile:plistPath];
        if (loadedArray) {
            NSMutableArray *groupList = [NSMutableArray arrayWithArray:loadedArray];
            for (NSDictionary *info in groupList) {
                if ([info[@"id"] integerValue] ==  [XDXShareInstance shareInstance].groupId.integerValue) {
                    self.groupInfo = [NSDictionary dictionaryWithDictionary:info];
                    [self.roomName setTitle:[NSString stringWithFormat:@"%@",info[@"name"]] forState:UIControlStateNormal];
                    [self.roomName sizeToFit];
                    [self.roomName setFrame:CGRectMake(24, 20, self.roomName.width, 32)];
                    
                    [self dealMemberGroupView];
                    break;
                }
            }
        }
    }
}



- (void)getGroupList
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
    [manager encryptedPOST:@"/system/group/grouplist"
    parameters:param
    success:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue]==200 ) {
            if ([responseObject[@"data"] count]>0) {
                
                BOOL isFound = NO;
                for (NSDictionary *info in responseObject[@"data"]) {
                    if ([info[@"id"] integerValue]==[XDXShareInstance shareInstance].groupId.integerValue) {
                        self.groupInfo = [NSDictionary dictionaryWithDictionary:info];
                        [self.roomName setTitle:[NSString stringWithFormat:@"%@",info[@"name"]] forState:UIControlStateNormal];
                        [self.roomName sizeToFit];
                        [self.roomName setFrame:CGRectMake(24, 20, self.roomName.width, 32)];
                        
                        [self dealMemberGroupView];
                        isFound = YES;
                    }
                }
                
                if (isFound==NO) {
                    NSDictionary *info = [responseObject[@"data"] firstObject];
                    self.groupInfo = [NSDictionary dictionaryWithDictionary:info];
                    [self.roomName setTitle:[NSString stringWithFormat:@"%@",info[@"name"]] forState:UIControlStateNormal];
                    [self.roomName sizeToFit];
                    [self.roomName setFrame:CGRectMake(24, 20, self.roomName.width, 32)];
                    
                    [self dealMemberGroupView];
                }
               
//                NSMutableArray *actionArray = [NSMutableArray array];
//                UIAction *action = [UIAction actionWithTitle:@"家庭管理" image:[UIImage imageNamed:@"manage"] identifier:nil handler:^(__kindof UIAction * _Nonnull action) {
//                    HomeManageViewController *vc = [[HomeManageViewController alloc] init];
//                    vc.hidesBottomBarWhenPushed = YES;
//                    [self.navigationController pushViewController:vc animated:YES];
//                    vc.HomeManageDeleteBlock = ^(NSString *groupId) {
//                        if ([[XDXShareInstance shareInstance].groupId integerValue] == groupId.integerValue) {
//                            [self getGroupList];
//                        }
//                    };
//                }];
//                for (NSDictionary *groupInfo in self.groupList) {
//                    UIAction *action = [UIAction actionWithTitle:groupInfo[@"name"] image:nil identifier:nil handler:^(__kindof UIAction * _Nonnull action) {
//                        self.groupInfo = [NSDictionary dictionaryWithDictionary:groupInfo];
//                        [self.roomName setTitle:[NSString stringWithFormat:@"%@",self.groupInfo[@"name"]] forState:UIControlStateNormal];
//                        [self.roomName sizeToFit];
//                        [self.roomName setFrame:CGRectMake(24, 20, self.roomName.width, 32)];
//                        [self dealMemberGroupView];
//                    }];
//                    if ([groupInfo[@"membership"] isKindOfClass:[NSDictionary class]]) {
//                        if ([groupInfo[@"membership"][@"planType"] integerValue]==3) {
//                            action.subtitle = @"黄金会员";
//                        }else if ([groupInfo[@"membership"][@"planType"] integerValue]==2){
//                            action.subtitle = @"白银会员";
//                        }else if ([groupInfo[@"membership"][@"planType"] integerValue]==1){
//                            action.subtitle = @"亲密会员";
//                        }
//                    }
//                    if ([groupInfo[@"id"] integerValue]==[self.groupInfo[@"id"] integerValue]) {
//                        action.state = UIMenuElementStateOn;
//                        
//                    }
//                    [actionArray addObject:action];
//                }
//                if (@available(iOS 14.0, *)) {
//                    if (@available(iOS 15.0, *)) {
//                        UIMenu *selectionGroup = [UIMenu menuWithTitle:@"" image:nil identifier:nil options:(UIMenuOptionsSingleSelection | UIMenuOptionsDisplayInline) children:actionArray];
//                        self.homeButton.menu = [UIMenu menuWithTitle:@"切换家庭" image:nil identifier:nil options:0 children:@[selectionGroup,action]];
//                    }
//                }
            }
        }
    }
    failure:^(NSError *aError) {
        
    }];
}

- (void)dealMemberGroupView
{
    if ([self.groupInfo[@"membership"] isKindOfClass:[NSDictionary class]]) {
        self.roomIcon.x = _roomName.maxX+4;
        self.arrow.x = _roomIcon.maxX+4;
        self.roomIcon.hidden = NO;
        self.quickCash.hidden = NO;
        self.cashTitle.hidden = NO;
        self.cashName.hidden = NO;
        [self.cashView setFrame:CGRectMake(6, _homeView.maxY+12, SCREEN_WIDTH-12, (SCREEN_WIDTH-12)*0.2974)];
        if ([self.groupInfo[@"membership"][@"planType"] integerValue]==1) {
            self.roomIcon.image = [UIImage imageNamed:@"icon_close"];
            self.cashView.image = [UIImage imageNamed:@"member_close"];
            [self.quickCash setBackgroundImage:[UIImage imageNamed:@"quick_cash_close"] forState:UIControlStateNormal];
            self.cashName.text = @"亲密会员";
        }else if ([self.groupInfo[@"membership"][@"planType"] integerValue]==2) {
            self.roomIcon.image = [UIImage imageNamed:@"icon_silver"];
            self.cashView.image = [UIImage imageNamed:@"member_silver"];
            [self.quickCash setBackgroundImage:[UIImage imageNamed:@"quick_cash_silver"] forState:UIControlStateNormal];
            self.cashName.text = @"白银会员";
        }if ([self.groupInfo[@"membership"][@"planType"] integerValue]==3) {
            self.roomIcon.image = [UIImage imageNamed:@"icon_gold"];
            self.cashView.image = [UIImage imageNamed:@"member_gold"];
            [self.quickCash setBackgroundImage:[UIImage imageNamed:@"quick_cash_gold"] forState:UIControlStateNormal];
            self.cashName.text = @"黄金会员";
        }
    }else{
        [self.cashView setFrame:CGRectMake(16, _homeView.maxY+12, SCREEN_WIDTH-32, (SCREEN_WIDTH-32)*0.3081)];
        self.cashView.image = [UIImage imageNamed:@"cash"];
        self.roomIcon.hidden = YES;
        self.quickCash.hidden = YES;
        self.cashTitle.hidden = YES;
        self.cashName.hidden = YES;
        
        self.arrow.x = _roomName.maxX+4;
    }
}

- (void)getUserInfo
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
    [manager encryptedPOST:@"/system/user/getInfo"
    parameters:param
    success:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue]==200 ) {
            [self.head sd_setImageWithURL:[NSURL URLWithString:responseObject[@"data"][@"avatar"]]];
            if ([responseObject[@"data"][@"nickName"] isKindOfClass:[NSString class]] && [responseObject[@"data"][@"nickName"] length]>0) {
                self.nickName.text = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"nickName"]];
            }
        }
    }
    failure:^(NSError *aError) {
        
    }];
}

@end
